<template>
  <a-drawer title="点击测试" :width="480" :visible="visible" :closable="true" @close="handleClose" placement="right"
    class="test-drawer">
    <div class="test-form" v-if="!showResult">
      <!-- 模型信息 -->
      <div class="form-section">
        <div class="section-title">模型信息</div>
        <div class="model-info">
          <div class="info-item">
            <span class="label">模型名称:</span>
            <span class="value">{{ (modelData && modelData.modelName) || '-' }}</span>
          </div>
          <div class="info-item">
            <span class="label">UUID:</span>
            <span class="value">{{ (modelData && modelData.modelUuid) || '-' }}</span>
          </div>
          <div class="info-item">
            <span class="label">模型版本:</span>
            <span class="value">{{ (modelData && modelData.version) || '-' }}</span>
          </div>
        </div>
      </div>

      <!-- IP地址选择 -->
      <div class="form-section">
        <div class="section-title">IP地址</div>
        <a-select v-model="selectedIp" placeholder="请选择IP" style="width: 100%" :loading="loading">
          <a-select-option v-for="ip in ipList" :key="ip" :value="ip">
            {{ ip }}
          </a-select-option>
        </a-select>
      </div>

      <!-- 发送次数 -->
      <div class="form-section">
        <div class="section-title">发送次数</div>
        <a-input-number v-model="sendCount" :min="1" :max="100" style="width: 100%" placeholder="1" />
      </div>

      <!-- 平均耗时阈值 -->
      <div class="form-section">
        <div class="section-title">平均耗时阈值</div>
        <div class="threshold-input">
          <a-input-number v-model="timeThreshold" :min="1" style="width: calc(100% - 30px)" placeholder="1" />
          <span class="unit">ms</span>
        </div>
      </div>

      <!-- 是否写日志 -->
      <div class="form-section">
        <div class="section-title">是否写日志</div>
        <a-switch v-model="writeLog" />
      </div>

      <!-- 参数列表 -->
      <div class="form-section">
        <div class="section-title">参数列表</div>
        <div class="param-list">
          <div v-for="(param, index) in paramList" :key="index" class="param-item">
            <div class="param-label">{{ param.dName || param.name }}:</div>
            <a-input :value="param.value == '-999' ? '' : param.value" @input="handleParamInput(param, $event)"
              :placeholder="`请输入${param.dName || param.name}`" class="param-input" />
          </div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="form-actions">
        <a-button type="primary" @click="handleTest" :loading="testing" block> 点击测试 </a-button>
      </div>
    </div>

    <!-- 测试结果 -->
    <div v-if="showResult && testResult" class="test-result">
      <div class="result-header">
        <div class="header-left">
          <a-icon type="experiment" class="result-icon" />
          <span class="result-title">测试结果</span>
        </div>
        <a-button type="link" @click="backToForm" class="back-btn">
          <a-icon type="arrow-left" />
          重新测试
        </a-button>
      </div>

      <!-- 测试状态 -->
      <div class="result-status">
        <a-alert :message="testResult.success ? '模型测试通过，可发起上线' : testResult.message"
          :type="testResult.success ? 'success' : 'error'" show-icon class="status-alert" />
      </div>

      <!-- 测试统计 -->
      <div class="result-stats">
        <div class="stat-row">
          <div class="stat-item highlight">
            <span class="stat-label">预测次数:</span>
            <span class="stat-value">{{ testResult.callTimes || 0 }}</span>
          </div>
        </div>

        <div class="stat-row">
          <div class="stat-item">
            <span class="stat-label">成功次数:</span>
            <span class="stat-value">{{ testResult.successTimes || 0 }}</span>
          </div>
        </div>

        <div class="stat-row">
          <div class="stat-item">
            <span class="stat-label">失败次数:</span>
            <span class="stat-value">{{ testResult.failedTimes || 0 }}</span>
          </div>
        </div>

        <div class="stat-row">
          <div class="stat-item">
            <span class="stat-label">总耗时:</span>
            <span class="stat-value">{{ testResult.totalSpendTimes || 0 }}</span>
            <span class="stat-unit">ms</span>
          </div>
        </div>

        <div class="stat-row">
          <div class="stat-item">
            <span class="stat-label">平均耗时:</span>
            <span class="stat-value">{{ testResult.avgSpendTimes || 0 }}</span>
            <span class="stat-unit">ms</span>
          </div>
        </div>
      </div>

      <!-- 预测结果详情 -->
      <div class="result-details">
        <div class="detail-label">预测结果:</div>
        <div class="detail-content">
          <a-textarea :value="formatCallResults(testResult.callResults)" :rows="8" readonly class="result-textarea" />
        </div>
      </div>
    </div>
  </a-drawer>
</template>

<script>
import { modelInput } from '@/api/operatorCheck'

export default {
  name: 'TestPop',
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    modelData: {
      type: Object,
      default: () => ({}),
    },
    modelType: {
      type: String,
      default: '',
    },
    modelApi: {
      type: Object,
      default: null,
    },
  },
  data() {
    return {
      loading: false,
      testing: false,
      selectedIp: '',
      sendCount: 1,
      timeThreshold: 1,
      writeLog: false,
      ipList: [],
      paramList: [],
      testResult: null,
      showResult: false,
    }
  },
  watch: {
    visible(newVal) {
      if (newVal) {
        this.showResult = false
        this.loadTestData()
      }
    },
  },
  methods: {
    async loadTestData() {
      try {
        this.loading = true
        const params = {
          modelUuid: (this.modelData && (this.modelData.modelUuid || this.modelData.uuid)) || '',
          version: (this.modelData && this.modelData.version) || '',
        }

        const response = await modelInput(params)
        if (response.success && response.data) {
          // 设置IP列表
          this.ipList = response.data.ips || []
          if (this.ipList.length > 0) {
            this.selectedIp = this.ipList[0]
          }

          // 解析参数列表
          if (response.data.inputData) {
            try {
              const inputData = JSON.parse(response.data.inputData)
              this.paramList = inputData.map((item) => ({
                ...item,
                value: '',
                // value: item.defaultValue !== undefined && item.defaultValue !== null && item.defaultValue !== '-999' ? item.defaultValue : ''
              }))
            } catch (error) {
              console.error('解析参数数据失败:', error)
              this.paramList = []
            }
          }
        } else {
          this.$message.error(response.data || '获取测试数据失败')
        }
      } catch (error) {
        console.error('加载测试数据失败:', error)
        this.$message.error('加载测试数据失败')
      } finally {
        this.loading = false
      }
    },

    async handleTest() {
      try {
        // 验证必填项
        if (!this.selectedIp) {
          this.$message.warning('请选择IP地址')
          return
        }

        // 验证参数
        const emptyParams = this.paramList.filter((param) => !param.value && param.value !== 0)
        if (emptyParams.length > 0) {
          this.$message.warning(`请填写参数: ${emptyParams.map((p) => p.dName || p.name).join(', ')}`)
          return
        }

        this.testing = true
        this.showResult = false

        // 构建测试参数
        const testParams = {
          callTimes: this.sendCount,
          avgThreshold: this.timeThreshold,
          ip: this.selectedIp,
          modelType: (this.modelData && this.modelData.modelType) || '',
          modelUuid: (this.modelData && (this.modelData.modelUuid || this.modelData.uuid)) || '',
          version: (this.modelData && this.modelData.version) || '',
        }

        // 添加参数列表中的参数
        this.paramList.forEach((param) => {
          testParams[param.name] = param.value
        })

        console.log('测试参数:', testParams)
        // 调用测试接口
        const response = await this.modelApi.modelCalculate(testParams)

        if (response.success && response.data) {
          this.testResult = response.data
          this.showResult = true
          // this.$message.success(response.message || '测试完成')
          this.$emit('test-complete', response.data)
        } else {
          this.$message.error(response.data || response.message || '测试失败')
        }
      } catch (error) {
        console.error('测试失败:', error)
        this.$message.error('测试失败')
      } finally {
        this.testing = false
      }
    },

    handleParamInput(param, event) {
      param.value = event.target.value
    },

    handleClose() {
      this.$emit('close')
    },

    backToForm() {
      this.showResult = false
      this.testResult = null
    },

    formatCallResults(callResults) {
      if (!callResults || !Array.isArray(callResults)) {
        return ''
      }

      return callResults
        .map((result, index) => {
          const lines = []
          lines.push(`调用 ${index + 1}:`)

          Object.keys(result).forEach((key) => {
            const value = result[key]
            if (typeof value === 'object' && value !== null) {
              lines.push(`  ${key}: ${JSON.stringify(value)}`)
            } else {
              lines.push(`  ${key}: ${value}`)
            }
          })

          return lines.join('\n')
        })
        .join('\n\n')
    },
  },
}
</script>

<style lang="less" scoped>
.test-drawer {
  :deep(.ant-drawer-header) {
    border-bottom: 1px solid #e8e8e8;
    padding: 16px 24px;
  }

  :deep(.ant-drawer-body) {
    padding: 0;
  }
}

.test-form {
  padding: 24px;
  height: 100%;
  overflow-y: auto;

  .form-section {
    margin-bottom: 24px;

    .section-title {
      font-size: 14px;
      font-weight: 600;
      color: #333;
      margin-bottom: 12px;
      display: flex;
      align-items: center;

      &::before {
        content: '';
        width: 3px;
        height: 14px;
        background: #1890ff;
        margin-right: 8px;
        border-radius: 2px;
      }
    }
  }

  .model-info {
    background: #fafafa;
    padding: 16px;
    border-radius: 6px;
    border: 1px solid #e8e8e8;

    .info-item {
      display: flex;
      margin-bottom: 8px;

      &:last-child {
        margin-bottom: 0;
      }

      .label {
        width: 80px;
        color: #666;
        font-size: 13px;
      }

      .value {
        flex: 1;
        color: #333;
        font-size: 13px;
        word-break: break-all;
      }
    }
  }

  .threshold-input {
    display: flex;
    align-items: center;

    .unit {
      margin-left: 8px;
      color: #666;
      font-size: 14px;
    }
  }

  .param-list {
    .param-item {
      display: flex;
      vertical-align: middle;
      margin-bottom: 16px;

      &:last-child {
        margin-bottom: 0;
      }

      .param-label {
        text-align: right;
        padding-right: 8px;
        width: 120px;
        font-size: 13px;
        color: #666;
        margin-bottom: 6px;
        line-height: 32px;
      }

      .param-input {
        width: calc(100% - 120px);
      }
    }
  }

  .form-actions {
    margin-top: 32px;
    padding-top: 24px;
    border-top: 1px solid #e8e8e8;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .test-drawer {
    :deep(.ant-drawer) {
      width: 100% !important;
    }
  }

  .test-form {
    padding: 16px;
  }
}

/* 测试结果样式 */
.test-result {
  padding: 20px;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.header-left {
  display: flex;
  align-items: center;
}

.result-icon {
  font-size: 18px;
  color: #1890ff;
  margin-right: 8px;
}

.result-title {
  font-size: 16px;
  font-weight: 600;
  color: #262626;
}

.back-btn {
  display: flex;
  align-items: center;
  padding: 4px 8px;
  border-radius: 4px;
  transition: all 0.3s;
}

.back-btn:hover {
  background-color: #f5f5f5;
}

.back-btn .anticon {
  margin-right: 4px;
}

.result-status {
  margin-bottom: 20px;
}

.status-alert {
  border-radius: 6px;
}

.result-stats {
  background: #fafafa;
  border-radius: 6px;
  padding: 16px;
  margin-bottom: 20px;
}

.stat-row {
  display: flex;
  margin-bottom: 12px;
}

.stat-row:last-child {
  margin-bottom: 0;
}

.stat-item {
  display: flex;
  align-items: center;
  flex: 1;
}

.stat-item.highlight {
  font-weight: 600;
}

.stat-label {
  color: #666;
  margin-right: 8px;
  min-width: 80px;
}

.stat-value {
  color: #262626;
  font-weight: 500;
  margin-right: 4px;
}

.stat-unit {
  color: #999;
  font-size: 12px;
}

.result-details {
  margin-top: 20px;
}

.detail-label {
  color: #666;
  margin-bottom: 8px;
  font-weight: 500;
}

.detail-content {
  border-radius: 6px;
  overflow: hidden;
}

.result-textarea {
  border-radius: 6px !important;
  font-family: 'Courier New', monospace;
  font-size: 12px;
  line-height: 1.5;
}
</style>
